package com.banmao.youZone.aop.delayedResponse;

import com.banmao.youZone.aop.delayedResponse.annotation.DelayedResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Slf4j
@Aspect
public class DelayedAOP {

    @Pointcut(value = "@annotation(com.banmao.youZone.aop.delayedResponse.annotation.DelayedResponse)")
    public void getPointcut() {
    }


    @Around("getPointcut()")
    public Object target(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("[DelayedAOP]delay Response, {}", this);
        long start = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DelayedResponse annotation = method.getAnnotation(DelayedResponse.class);

        Object proceed = joinPoint.proceed();
        if (annotation == null) {
            return proceed;
        }

        long end = System.currentTimeMillis();
        long cost = end - start;
        log.info("[DelayedAOP]method:{},cost:{}", method.getName(), cost);
        if (cost < annotation.lessThan()) {
            Thread.sleep(annotation.delayedTime());
        }

        return proceed;
    }



}
